import React, {Component, Fragment} from 'react'
// import ReactQuill,{Quill}from 'react-quill';
import Quill from "quill";
import "quill/dist/quill.snow.css";
import style from './editors_content.css'
// import 'react-quill/dist/quill.snow.css';
import btn_article_market from './img/btn_article_market.svg'
import btn_article_img_insert from './img/btn_article_img_insert.svg'
import btn_article_font_setting from './img/btn_article_font_setting.svg'
import btn_article_link_insert from './img/btn_article_link_insert.svg'
// import {katex} from 'katex';
// import {insertStar} from "./insertstar";
import {CustomToolbar} from "./customtoolbar";
import './index.scss'


/*
        * Quill editor formats
        * See https://quilljs.com/docs/formats/
        */
const formats = [
    // "background",
    "bold",
    // "color",
    "font",
    // "code",
    // "italic",
    // "italic",
    "link",
    "size",
    // "strike",
    // "script",
    // "underline",
    // "blockquote",
    // "header",
    // "indent",
    // "list",
    // "align",
    // "direction",
    // "code-block",
    // "formula",
    "image"
];

// Quill.register(katex,true);

// let maxTextSize = 10;
const $android = window.$android;

const article = 'article';
const course = 'course';

export class EditorPanelWithQuill extends Component {
    constructor(props) {
        super(props);
        this.mToolbar = React.createRef();
        // this.myRef = React.createRef();
        this.state = {
            text: '',
            softHeight: 0,
            userInfo: '',
            textSize: 0,
            maxTextSize: 1000000000,
            type: course,
            placeholder: "写点什么...",
            toolbar_down_show: false,
        };

        // You can also pass a Quill Delta here
        this.modules = {
            toolbar: {
                container: "#toolbar",
                handlers: {
                    insertStar: this.getHtmlValue
                }

            },
            clipboard: {
                matchVisual: true,
            }
        };
        //    图片压缩
        //    https://github.com/fengyuanchen/compressorjs

        // react-quill
        // https://github.com/zenoamaro/react-quill#unprivileged-editor
    }


    componentDidMount() {

        window.onSoftHeight = this.onSoftHeight;

        window.onLinkInsert = this.onLinkInsert;

        window.onLinkMarket = this.onLinkMarket;

        window.onLinkImgInsert = this.onLinkImgInsert;

        window.onSetMaxTextSize = this.onSetMaxTextSize;

        window.onSetContentType = this.onSetContentType;

        let {text, placeholder} = this.state;

        // let {textSize} = this.state;
        // 配置项，在Quill 官网上有详细说明
        const options = {
            debug: "warn",
            theme: "snow",
            modules: { // 自定义 toolbar 填写这个属性， 值写上 div 的 id
                toolbar: "#toolbar"
            },
            placeholder: placeholder,
            // readOnly:textSize>MaxTextSize
        };
        // 实例化 Quill 并且储存在实例原型上
        this.editor = new Quill("#editor", options);
        // this.editor.addContainer('custom_editor');
        // 实现输入受控，从state中读取html字符串写入编辑器中

        // 判断value中是否有值，如果有那么就写入编辑器中
        if (text) this.editor.clipboard.dangerouslyPasteHTML(text);
        // 设置事件，change事件，
        this.editor.on('text-change', this.handleChange);
        this.editor.focus();

        window.setHtmlContent = this.setHtmlContent;

        window.onSetPlaceholder = this.onSetPlaceholder;
    }

    onSoftHeight = (height) => {

        this.setState({
            softHeight: height
        });
        this.editor.focus();
        // if (height<=0) {
        //     this.editor.root.style.height =90+'%'
        // }else {
        //     this.editor.root.style.height =this.mToolbar.current.style.top+'px'
        // }
        this.editor.root.style.height = (90 - this.state.softHeight * 100) + '%'

    };

    render() {
        let {softHeight, toolbar_down_show, textSize, maxTextSize, type} = this.state;

        return (
            <Fragment>

                <div ref={this.mToolbar} className='customToolbarDiv' style={{bottom: softHeight * 100 + '%'}}>
                    {/*<CustomToolbar id='customToolbar'/>*/}
                    <div id="toolbar" className='toolbar_js'>
                        <div className='toolbar_top'>

                            {/*<button className='ql-image'/>*/}

                            <button onClick={() => this.handleImgInsert()}>
                                <img src={btn_article_img_insert} alt=''/>
                            </button>

                            {
                                type === article ?
                                    (
                                        <div>
                                            <button onClick={() => this.handleMarket()}>
                                                <img src={btn_article_market} alt=''/>
                                            </button>

                                            <button onClick={() => this.handleLinkInsert()}>
                                                <img src={btn_article_link_insert} alt=''/>
                                            </button>
                                        </div>
                                    ) : (null)

                            }

                            <button onClick={() => this.handleFontSetting()}>
                                <img src={btn_article_font_setting} alt=''/>
                            </button>

                            <span>{textSize}/{maxTextSize}</span>

                        </div>

                        <div className={toolbar_down_show ? 'toolbar_down_show' : 'toolbar_down_hid'}>
                            <button className="ql-bold"/>
                            <button className="ql-underline"/>
                            <button id="small" className="ql-size" value="small">小</button>
                            <button id="large" className="ql-size" value="large">中</button>
                            <button id="huge" className="ql-size" value="huge">大</button>
                            <button id="normal" className="ql-size">默认</button>
                        </div>

                    </div>
                </div>
                {/*<div className="text-editor">*/}
                <div id="editor" className='content_Div' style={

                    {
                        // "#custom_editor":"img{ width:'100%' }"
                    }
                }>


                    {/*<div id='custom_editor' className='ql-custom'>*/}

                    {/*</div>*/}


                </div>
            </Fragment>

        )
    }

    onSetPlaceholder = (placeholder) => {
        // this.setState({
        //     placeholder: placeholder
        // })
        this.editor.options.placeholder = placeholder
    };

    onSetContentType = (type) => {
        let contentType = type === article ? article : course;
        this.setState({
            type: contentType
        })
    };


    onSetMaxTextSize = (maxSize) => {
        this.setState({
            maxTextSize: maxSize
        })
    };

    setHtmlContent = (html) => {
        this.setState({
            text: html
        });
        let cursorPosition = this.editor.getSelection().index;

        this.editor.clipboard.dangerouslyPasteHTML(cursorPosition, html);
        this.editor.setSelection(cursorPosition + html.length);//光标位置加1
    };

    handleFontSetting = () => {
        let {toolbar_down_show} = this.state;
        this.setState({
            toolbar_down_show: !toolbar_down_show,
        });
        this.editor.focus();
        console.log("height" + this.mToolbar.current.height);
        // this.editor.root.style.bottom =this.mToolbar.current.style.height+'px'
        let toolbar_down_height = this.state.toolbar_down_show ? 32 : 0;
        this.editor.root.style.height = this.editor.root.style.height + toolbar_down_height
    };

    handleLinkInsert = () => {
        this.editor.focus();
        if ($android) {
            $android.linkInsert()
        } else {
            let cursorPosition = this.editor.getSelection().index;
            this.editor.insertText(cursorPosition, 'BaiDu', 'link', 'https://www.baidu.com');
            this.editor.setSelection(cursorPosition + 'BaiDu'.length)
        }
    }
    ;

    handleMarket = () => {
        this.editor.focus();
        if ($android) {
            $android.marketInsert()
        }
    };


    handleImgInsert = () => {
        this.editor.focus();
        if ($android) {
            $android.imgInsert()
        } else {
            let cursorPosition = this.editor.getSelection().index;
            // let str = `<p><img src=http://img5.imgtn.bdimg.com/it/u=1236448464,3135499563&fm=15&gp=0.jpg width='100%' alt=''/><br/></p>`;
            // this.editor.clipboard.dangerouslyPasteHTML(cursorPosition, str);

            // this.editor.setSelection(cursorPosition + 1);//光标位置加1
            this.editor.insertEmbed(cursorPosition, 'image', 'http://img5.imgtn.bdimg.com/it/u=1236448464,3135499563&fm=15&gp=0.jpg');
            this.editor.setSelection(cursorPosition + 1)
        }
    };

    onLinkInsert = (link, text) => {

        // let str = `<a href=${link}>${text}</a>`;

        let cursorPosition = this.editor.getSelection().index;
        this.editor.insertText(cursorPosition, text, 'link', link);
        // this.editor.clipboard.dangerouslyPasteHTML(cursorPosition, str);
        this.editor.setSelection(cursorPosition + text.length);//光标位置加1

    };

    onLinkMarket = (market, text) => {
        // let str = ` <a href=${market}>${text}</a>`;
        let cursorPosition = this.editor.getSelection().index;
        // this.editor.clipboard.dangerouslyPasteHTML(cursorPosition, str);
        this.editor.insertText(cursorPosition, text, 'link', market);
        this.editor.setSelection(cursorPosition + text.length);//光标位置加1

    };

    onLinkImgInsert = (imgPath) => {
        // let paths = JSON.stringify(imgPath);
        // console.log("imgPath===" + paths);
        // let str = `<p><img src=${imgPath} width='100%' alt=''/><br/></p>`;

        let cursorPosition = this.editor.getSelection().index;
        this.editor.insertEmbed(cursorPosition, 'image', imgPath);
        // this.editor.clipboard.dangerouslyPasteHTML(cursorPosition, str);

        this.editor.setSelection(cursorPosition + 1);//光标位置加1

    };


    handleChange = (delta, oldDelta, source) => {

        let content = this.editor.root.innerHTML;

        console.log(this.editor.getLength());
        // let length = content.replace(/<[^<>]+>/g, "").length;
        let length = this.editor.getText(0, this.editor.getLength()).trim().length;
        console.log("length===" + length);

        console.log("source==="+source);

        let {maxTextSize} = this.state;

        if (length > maxTextSize) {

            this.editor.deleteText(maxTextSize, this.editor.getLength());

            content = this.editor.root.innerHTML;
            length = this.editor.getText(0, this.editor.getLength()).trim().length;
            if ($android) {
                $android.outOfMaxTextSize(maxTextSize)
            }
        } else if (length <= 0) {
            content = ""
        }
        this.setState({
            text: content,
            textSize: length
        });

        let content_str = "";
        if (length > 0) {
            content_str = `<div style="word-break: break-all;w">${this.state.text}
                             <style type="text/css"> 
                             img{width: 100%;} 
                             .ql-size-huge{font-size: 2.5em}
                             .ql-size-large{font-size: 1.5em}
                             .ql-size-small：{font-size: 0.75em}
                             </style>
	                        </div>`;
        }

        if ($android) {
            $android.getHtmlContent(content_str)
        }
    }
}